package com.ylb.rent.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * @AUTHOR:游李滨
 * @DATE:2023/6/30 19:15
 */
public class QrCodeUtil {
    /**
     *  二维码内容, 长 , 宽 , 输出流
     *
     *
     * */
    public static void generateQrCode(String content, int width, int height, OutputStream output) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height,hints);
        BufferedImage image = new BufferedImage(width,height ,BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                // 设置黑白相见的颜色
                image.setRGB(x, y, encode.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        // 输出jpg格式图片
        ImageIO.write(image, "jpg", output);
    }
    public static void generateQrCode(String content, int width, int height,HttpServletResponse response) throws IOException, WriterException {
        //            /设置response
        response.setContentType("image/png");
        generateQrCode(content,width,height,response.getOutputStream());
    }
    public static void generateQrCode(String content,int size,HttpServletResponse response) throws IOException, WriterException {
        //            /设置response

        generateQrCode(content,size,size,response);
    }
    public static void generateQrCode(String content,HttpServletResponse response) throws IOException, WriterException {
        //            /设置response

        generateQrCode(content,200,200,response);
    }
}
